'''
Created on 12.09.2009

@author: ankstoo
'''

from pygs.logger import logger
from pygs.services.security.authentication import Authentication
from pygs.services.security.securityTokenData import *
import time
import uuid

class AuthenticationStrategy(object):
    '''
    '''
    
    def __init__(self, authentication):
        object.__init__(self)
        self.authentication = authentication
        
    def checkUser(self, params):
        return {"userExists": False, "userValid": False, "userId": None}
    
    def tryLogin(self, params):
        userInfo = self.checkUser(params)
        if userInfo["userExists"] and userInfo["userValid"] and userInfo["userId"]:
            tokenInfo = self.registerUser(userInfo["userId"], params)
            userInfo.update(tokenInfo)
        return userInfo

    def generateToken(self, userId, params):
        return uuid.uuid1()     

    def registerUser(self, userId, params):
        # calc expiration date
        expirationDate = time.strftime("%Y-%m-%d %X", time.localtime(time.time() + self.authentication.expirationTime * 60))
        logger.debug("Calculated expiration date: '%s' for user '%s'." % (expirationDate, userId))
        
        # get new user token
        token = self.generateToken(userId, params)
        self.authentication.persistence().saveToken(token, TokenData(None, userId, expirationDate))
        logger.log("Got token '%s' for user '%s'. Token expire: %s." %
            (token, userId, expirationDate))
        return {"token": token, "expirationDate": expirationDate}
    
    @classmethod
    def register(cls, mode, isDefault = False):
        strategys.register(mode, cls, isDefault)

class AuthenticationSecured(Authentication):
    '''
    ''' 
    
    # Session expirationTime in minutes
    expirationTime = 30    
    
    def startup(self, params = None):
        Authentication.startup(self, params)
        # get expirationTime from params
        if params and params.has_key("expirationTime"):
            self.expirationTime = params["expirationTime"]

    def shutdown(self):
        Authentication.shutdown(self)
        pass 
    
    def login(self, mode, params):
        strategy = strategys.getOrDefault(mode)
        assert(strategy)
        return strategy(self).tryLogin(params)
    
    def logout(self, token):
        res = self.persistence().deleteToken(token)
        logger.log("Token '%s' deleted." % token)
        return res  
    
    
class AuthenticationStrategys(object):
    
    def __init__(self):
        object.__init__(self)
        self.strategys = {}
        self.default = None
    
    def register(self, mode, strategy, isDefault = False):
        self.strategys[mode] = strategy
        if isDefault:
            self.default = strategy
    
    def get(self, mode):
        if mode in self.strategys:
            return self.strategys[mode]
        else:
            return None    
    
    def getDefault(self):
        return self.default
    
    def getOrDefault(self, mode):
        strategy = self.get(mode)
        if not strategy:
            strategy = self.getDefault
        return strategy
        
    
strategys = AuthenticationStrategys()

from pygs.services.security.authenticationStrategyRegistration import registerStrategys
registerStrategys()   